use winit::event::{WindowEvent, KeyboardInput, VirtualKeyCode, ElementState};

use crate::camera::Camera;

pub struct CameraControl {
    cmds: u32
}

impl CameraControl {
    pub fn new() -> Self {
        Self { cmds: 0 }
    }

    pub fn handle_events(&mut self, event: &WindowEvent) -> bool {
        match event {
            WindowEvent::KeyboardInput {
                input: KeyboardInput {
                    state,
                    virtual_keycode: Some(keycode),
                    ..
                },
                ..
            } => {
                let mut cmds = 0u32;
                let ok = match keycode {
                    VirtualKeyCode::Right  => { cmds |= Camera::CMD_ROT_RIGHT; true }
                    VirtualKeyCode::Left   => { cmds |= Camera::CMD_ROT_LEFT ; true }
                    VirtualKeyCode::Up     => { cmds |= Camera::CMD_ROT_UP   ; true }
                    VirtualKeyCode::Down   => { cmds |= Camera::CMD_ROT_DOWN ; true }
                    VirtualKeyCode::W      => { cmds |= Camera::CMD_FRONT    ; true }
                    VirtualKeyCode::S      => { cmds |= Camera::CMD_BACK     ; true }
                    VirtualKeyCode::D      => { cmds |= Camera::CMD_RIGHT    ; true }
                    VirtualKeyCode::A      => { cmds |= Camera::CMD_LEFT     ; true }
                    VirtualKeyCode::Space  => { cmds |= Camera::CMD_UP       ; true }
                    VirtualKeyCode::LShift => { cmds |= Camera::CMD_DOWN     ; true }
                    _ => false
                };
                if *state == ElementState::Pressed {
                    self.cmds |= cmds;
                } else {
                    self.cmds &= !cmds;
                }
                ok
            },
            _ => false
        }
    }

    pub fn update_camera(&self, camera: &mut Camera) {
        camera.handle_cmds(self.cmds, 0.02);
    }
}
